package net.xdclass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.ProductOrderStateEnum;
import net.xdclass.enums.StockTaskStateEnum;
import net.xdclass.feign.OrderFeignClient;
import net.xdclass.mapper.ProductMapper;
import net.xdclass.mapper.ProductTaskMapper;
import net.xdclass.model.ProductRecordMessage;
import net.xdclass.model.ProductTaskDO;
import net.xdclass.service.ProductTaskService;
import net.xdclass.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Classname ProductTaskServiceImpl
 * @Description TODO
 * @Date 2022/5/24 14:43
 * @Created by sunhao
 */
@Slf4j
@Service
public class ProductTaskServiceImpl implements ProductTaskService {

  @Autowired
  private ProductTaskMapper productTaskMapper;

  @Autowired
  private OrderFeignClient orderFeignClient;

  @Autowired
  private ProductMapper productMapper;

  @Override
  public boolean releaseProductRecord(ProductRecordMessage productRecordMessage) {
    JsonData jsonData = orderFeignClient.queryProductOrderState(productRecordMessage.getOutTradeNo());
    ProductTaskDO productTaskDO = productTaskMapper.selectById(productRecordMessage.getTaskId());
    if (null == productTaskDO) {
      log.info("工作单不存在 消息{}", productRecordMessage);
      return true;
    }
    if (jsonData.getCode() == 0) {
      String orderState = jsonData.getData().toString();
      if (orderState.equalsIgnoreCase(ProductOrderStateEnum.NEW.name())) {
        //订单状态为NEW 状态 需要重新投递
        log.warn("订单状态是NEW状态 重新投递{}", productTaskDO);
        return false;
      }
      if (orderState.equalsIgnoreCase(ProductOrderStateEnum.PAY.name())) {
        //订单状态为PAY 状态 需要修改工作单状态为 完成
        productTaskDO.setLockState(StockTaskStateEnum.FINISH.name());
        productTaskMapper.update(productTaskDO, new QueryWrapper<ProductTaskDO>().eq("id", productTaskDO.getId()));
        log.warn("订单已经支付 修改工作单状态为完成 {}", productTaskDO);
        return true;
      }
    }
    log.warn("订单不存在 或者 已经取消 修改工作单状态为取消 {}", productTaskDO);
    productTaskDO.setLockState(StockTaskStateEnum.CANCEL.name());
    productTaskMapper.update(productTaskDO, new QueryWrapper<ProductTaskDO>().eq("id", productTaskDO.getId()));
    //库存回收
    int rows = productMapper.releaseProductLock(productTaskDO.getProductId(), productTaskDO.getBuyNum());
    if (rows != 1) {
      log.warn("释放库存失败 重新投递{}", productTaskDO);
      return false;
    }
    return true;
  }
}
